<?php

class Module_Models_Docsend extends Zend_Db_Table_Abstract {
    protected $_name = "docsend";
    protected $_primary = "SendID";
    protected $_primary_name;
    public function __construct()
    {
        parent::__construct();
        $this->_primary_name = $this->_primary;
    }
    public function getAllDocsend($params) {
        $pagenum = $params['pagenum'];
        $pagesize = $params['pagesize'];
        $start = $pagenum * $pagesize;
		$status = $params['Status'];
		$sRole = $params['Role'];
		$sRolestatus = $params['RoleStatus'];
        $where ='1=1';
		//Lay theo trang thai
        if($status){
            $where .=" And Status='$status'";
        }
		//Lay theo quyen xem vb
        if(!$params['Permistion']){
            if($params['StaffID']){
				$StaffID = $params['StaffID'];
				$where .=" And SendID IN (Select DocID from draffhandlestaff where StaffID = '$StaffID' and Role='$sRole' and Status = '$sRolestatus')";
			}
        }
        // Filter
        if (isset($params['filterscount']))
        {
            $filterscount = $params['filterscount'];
            
            if ($filterscount > 0)
            {
                $where .= " And (";
                $tmpdatafield = "";
                $tmpfilteroperator = "";
                for ($i=0; $i < $filterscount; $i++)
                {
                    // get the filter's value.
                    $filtervalue = $params["filtervalue" . $i];
                    // get the filter's condition.
                    $filtercondition = $params["filtercondition" . $i];
                    // get the filter's column.
                    $filterdatafield = $params["filterdatafield" . $i];
                    // get the filter's operator.
                    $filteroperator = $params["filteroperator" . $i];
                    
                    if ($tmpdatafield == "")
                    {
                        $tmpdatafield = $filterdatafield;           
                    }
                    else if ($tmpdatafield <> $filterdatafield)
                    {
                        $where .= ")AND(";
                    }
                    else if ($tmpdatafield == $filterdatafield)
                    {
                        if ($tmpfilteroperator == 0)
                        {
                            $where .= " AND ";
                        }
                        else $where .= " OR ";  
                    }
                    
                    // build the "WHERE" clause depending on the filter's condition, value and datafield.
                    $where .= Clound_Public::getInstance()->getClauseByFilter($filtercondition, $filterdatafield, $filtervalue);
                                    
                    if ($i == $filterscount - 1)
                    {
                        $where .= ")";
                    }
                    
                    $tmpfilteroperator = $filteroperator;
                    $tmpdatafield = $filterdatafield;      
                }
            }
        }
        // Sort
		if($status=='DA_BAN_HANH'){
			$orders =' NumberMain DESC';
		}else{
			$orders =' SendID DESC';
		}
        if (isset($params['sortdatafield'])) {
            $sortfield = $params['sortdatafield'];
            $sortorder = $params['sortorder'];
            if ($sortorder != '') {
                if ($sortorder == "desc") {
                    $orders = " " . $sortfield . " DESC";
                } else if ($sortorder == "asc") {
                    $orders = " " . $sortfield . " ASC";
                }
            }
        }
        // Lay tong
        $getTotal = $this->select()->from($this, array())->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))->where($where);
        $rows = $this->getAdapter()->fetchRow($getTotal);
        $total_rows = $rows['total'];
        // Lay du lieu
		$query = $this->select()->from($this)->where($where)->order($orders)->limit($pagesize, $start);
        $rows = $this->getAdapter()->fetchAll($query);
		//convert data
		$objDate = new Clound_Datetime();
		$fileObj = new Clound_File(null,false);
		$count = sizeof($rows);
		$modelStaff = new Module_Models_DraffStaff();
		$sRole = 'GUI_NHAN_VB';
		$oCacheFile = new Clound_CacheFile();
		$arrDocType = $oCacheFile->getList('DM04');			
		$oCloundPublic = new Clound_Public();		
		for($i=0;$i<$count;$i++)
		{
			if($status=='DA_BAN_HANH'){
				$objDate->set($rows[$i]['SendDate'],'yyyy-MM-dd HH:mm:ss');
				$rows[$i]['SendDate'] = $objDate->ToDdMMyyyy();		
				$rows[$i]['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','SEND',$rows[$i]);	
				$rows[$i]['NumberMain'] = $rows[$i]['NumberMain'].$rows[$i]['NumberAdd'].'/'.$rows[$i]['Symbol'];
				$rows[$i]['ReceivedInfo'] = $rows[$i]['ReceivedInfo'].'; '.$modelStaff->getRopReceivedString($rows[$i]['SendID'],$sRole);
			}else{
				$rows[$i]['DocType'] = $oCloundPublic->getNameByCode($arrDocType, $rows[$i]['DocType']);
				$objDate->set($rows[$i]['DraffDate'],'yyyy-MM-dd HH:mm:ss');
				$rows[$i]['DraffDate'] = $objDate->ToDdMMyyyy();	
				$rows[$i]['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','DRAFF',$rows[$i]);
			}
		}
        $data[] = array(
            'TotalRows' => $total_rows,
            'Rows' => $rows
        );
        return $data;
    }

	public function getAllDocDraff($params) {
        $pagenum = $params['pagenum'];
        $pagesize = $params['pagesize'];
        $start = $pagenum * $pagesize;
		$status = $params['Status'];
        $where ='1=1';
		//Lay theo trang thai
        if($status){
            $where .=" And Status='$status'";
        }
		//Lay theo quyen xem vb
		$StaffID = $params['StaffID'];
		if($StaffID){
			$where .=" And StaffID='$StaffID'";
		}
        // Filter
        if (isset($params['filterscount']))
        {
            $filterscount = $params['filterscount'];
            
            if ($filterscount > 0)
            {
                $where .= " And (";
                $tmpdatafield = "";
                $tmpfilteroperator = "";
                for ($i=0; $i < $filterscount; $i++)
                {
                    // get the filter's value.
                    $filtervalue = $params["filtervalue" . $i];
                    // get the filter's condition.
                    $filtercondition = $params["filtercondition" . $i];
                    // get the filter's column.
                    $filterdatafield = $params["filterdatafield" . $i];
                    // get the filter's operator.
                    $filteroperator = $params["filteroperator" . $i];
                    
                    if ($tmpdatafield == "")
                    {
                        $tmpdatafield = $filterdatafield;           
                    }
                    else if ($tmpdatafield <> $filterdatafield)
                    {
                        $where .= ")AND(";
                    }
                    else if ($tmpdatafield == $filterdatafield)
                    {
                        if ($tmpfilteroperator == 0)
                        {
                            $where .= " AND ";
                        }
                        else $where .= " OR ";  
                    }
                    
                    // build the "WHERE" clause depending on the filter's condition, value and datafield.
                    $where .= Clound_Public::getInstance()->getClauseByFilter($filtercondition, $filterdatafield, $filtervalue);
                                    
                    if ($i == $filterscount - 1)
                    {
                        $where .= ")";
                    }
                    
                    $tmpfilteroperator = $filteroperator;
                    $tmpdatafield = $filterdatafield;      
                }
            }
        }
        // Sort
		if($status=='DA_BAN_HANH'){
			$orders =' NumberMain DESC';
		}else{
			$orders =' SendID DESC';
		}
        if (isset($params['sortdatafield'])) {
            $sortfield = $params['sortdatafield'];
            $sortorder = $params['sortorder'];
            if ($sortorder != '') {
                if ($sortorder == "desc") {
                    $orders = " " . $sortfield . " DESC";
                } else if ($sortorder == "asc") {
                    $orders = " " . $sortfield . " ASC";
                }
            }
        }

        // Lay tong
        $getTotal = $this->select()->from($this, array())->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))->where($where);
        $rows = $this->getAdapter()->fetchRow($getTotal);
        $total_rows = $rows['total'];
        // Lay du lieu
		$query = $this->select()->from($this)->where($where)->order($orders)->limit($pagesize, $start);
        $rows = $this->getAdapter()->fetchAll($query);
		//convert data
		$objDate = new Clound_Datetime();
		$fileObj = new Clound_File(null,false);
		$count = sizeof($rows);
		$modelStaff = new Module_Models_DraffStaff();
		$sRole = 'GUI_NHAN_VB';
		$oCacheFile = new Clound_CacheFile();
		$arrDocType = $oCacheFile->getList('DM04');			
		$oCloundPublic = new Clound_Public();		
		for($i=0;$i<$count;$i++)
		{
			if($status=='DA_BAN_HANH'){
				$objDate->set($rows[$i]['SendDate'],'yyyy-MM-dd HH:mm:ss');
				$rows[$i]['SendDate'] = $objDate->ToDdMMyyyy();		
				$rows[$i]['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','SEND',$rows[$i]);	
				$rows[$i]['NumberMain'] = $rows[$i]['NumberMain'].$rows[$i]['NumberAdd'].'/'.$rows[$i]['Symbol'];
				$rows[$i]['ReceivedInfo'] = $rows[$i]['ReceivedInfo'].'; '.$modelStaff->getRopReceivedString($rows[$i]['SendID'],$sRole);
			}else{
				$rows[$i]['DocType'] = $oCloundPublic->getNameByCode($arrDocType, $rows[$i]['DocType']);
				$objDate->set($rows[$i]['DraffDate'],'yyyy-MM-dd HH:mm:ss');
				$rows[$i]['DraffDate'] = $objDate->ToDdMMyyyy();	
				$rows[$i]['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','DRAFF',$rows[$i]);
			}
		}
        $data[] = array(
            'TotalRows' => $total_rows,
            'Rows' => $rows
        );
        return $data;
    }

	public function getAllRopDocDraff($params) {
        $pagenum = $params['pagenum'];
        $pagesize = $params['pagesize'];
        $start = $pagenum * $pagesize;
        $where ='1=1';
		//Lay theo quyen xem vb
		$StaffID = $params['StaffID'];
		if($StaffID){
			$where .=" And SendID IN (select DocID from worksend where StaffID = '$StaffID')";
		}
        // Filter
        if (isset($params['filterscount']))
        {
            $filterscount = $params['filterscount'];
            
            if ($filterscount > 0)
            {
                $where .= " And (";
                $tmpdatafield = "";
                $tmpfilteroperator = "";
                for ($i=0; $i < $filterscount; $i++)
                {
                    // get the filter's value.
                    $filtervalue = $params["filtervalue" . $i];
                    // get the filter's condition.
                    $filtercondition = $params["filtercondition" . $i];
                    // get the filter's column.
                    $filterdatafield = $params["filterdatafield" . $i];
                    // get the filter's operator.
                    $filteroperator = $params["filteroperator" . $i];
                    
                    if ($tmpdatafield == "")
                    {
                        $tmpdatafield = $filterdatafield;           
                    }
                    else if ($tmpdatafield <> $filterdatafield)
                    {
                        $where .= ")AND(";
                    }
                    else if ($tmpdatafield == $filterdatafield)
                    {
                        if ($tmpfilteroperator == 0)
                        {
                            $where .= " AND ";
                        }
                        else $where .= " OR ";  
                    }
                    
                    // build the "WHERE" clause depending on the filter's condition, value and datafield.
                    $where .= Clound_Public::getInstance()->getClauseByFilter($filtercondition, $filterdatafield, $filtervalue);
                                    
                    if ($i == $filterscount - 1)
                    {
                        $where .= ")";
                    }
                    
                    $tmpfilteroperator = $filteroperator;
                    $tmpdatafield = $filterdatafield;      
                }
            }
        }
        // Sort
		$orders =' SendID DESC';
        if (isset($params['sortdatafield'])) {
            $sortfield = $params['sortdatafield'];
            $sortorder = $params['sortorder'];
            if ($sortorder != '') {
                if ($sortorder == "desc") {
                    $orders = " " . $sortfield . " DESC";
                } else if ($sortorder == "asc") {
                    $orders = " " . $sortfield . " ASC";
                }
            }
        }

        // Lay tong
        $getTotal = $this->select()->from($this, array())->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))->where($where);
        $rows = $this->getAdapter()->fetchRow($getTotal);
        $total_rows = $rows['total'];
        // Lay du lieu
		$query = $this->select()->from($this)->where($where)->order($orders)->limit($pagesize, $start);
        $rows = $this->getAdapter()->fetchAll($query);
		//convert data
		$objDate = new Clound_Datetime();
		$fileObj = new Clound_File(null,false);
		$count = sizeof($rows);
		$oCacheFile = new Clound_CacheFile();
		$arrDocType = $oCacheFile->getList('DM04');			
		$oCloundPublic = new Clound_Public();		
		for($i=0;$i<$count;$i++)
		{
			$rows[$i]['DocType'] = $oCloundPublic->getNameByCode($arrDocType, $rows[$i]['DocType']);
			$objDate->set($rows[$i]['DraffDate'],'yyyy-MM-dd HH:mm:ss');
			$rows[$i]['DraffDate'] = $objDate->ToDdMMyyyy();	
			$rows[$i]['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','DRAFF',$rows[$i]);
		}
        $data[] = array(
            'TotalRows' => $total_rows,
            'Rows' => $rows
        );
        return $data;
    }
	
    public function isValid($data){
        $where = " Where ".$this->getAdapter()->quoteInto("$this->_primary_name <> ?", $data[$this->_primary_name])
                .$this->getAdapter()->quoteInto(" And DocType = ?",$data['DocType'])
				.$this->getAdapter()->quoteInto(" And SendDate = ?",$data['SendDate'])
				.$this->getAdapter()->quoteInto(" And NumberMain = ?",$data['NumberMain']);
    
        $rows = $this->getAdapter()->fetchRow("SELECT COUNT(*) as total FROM $this->_name ".$where);
        if($rows['total']){
            return false;
        }else{
            return true;
        }
        return $rows['total'];
    }    

	public function selectRow($id){
        if($id){
            $query = $this->select()->from($this)->where("$this->_primary_name = ?", $id);
            $rows = $this->getAdapter()->fetchRow($query);
        }else{
            $rows = array();
        }
        return $rows;
    }
	
    public function deleteRows($listId){
        $aListID = explode(',', $listId);
        $where = $this->getAdapter()->quoteInto("$this->_primary_name IN (?)", $aListID);
        $aResult = array('errors'=>!$this->delete($where),'mgs'=>$where);
        return $aResult;
    }
}
